package org.fu.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fu.crowd.constant.CrowdConstant;
import org.fu.crowd.entity.Admin;
import org.fu.crowd.entity.AdminExample;
import org.fu.crowd.exception.LoginFailedException;
import org.fu.crowd.exception.SaveAdminException;
import org.fu.crowd.mapper.AdminMapper;
import org.fu.crowd.service.api.AdminService;
import org.fu.crowd.utils.CrowdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;





    /**
     * 查询所有用户
     * @return 查询到的用户
     */
    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(null);
    }






    /**
     *     根据账号密码查询用户信息
     * @param admin 用户信息对象
     * @return 查询结果   null为没有查询到
     */
    @Override
    public Admin getAdminByAcctAndPsw(Admin admin) {
        //根据账号密码查询用户信息
        AdminExample adminExample = new AdminExample();
        //查询条件拼接
        adminExample.createCriteria().andLoginAcctEqualTo(admin.getLoginAcct());
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        //判断是否查询成功
        if (adminList==null || adminList.size()==0){
            //若失败(用户不存在),则抛异常，交给异常处理
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (adminList.size()>1){
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        //若成功，将密码取出
        Admin getAdmin = adminList.get(0);
        String userPwdDB = getAdmin.getUserPswd();
        //将表单的明文密码进行加密
        String userPwd = CrowdUtils.md5(admin.getUserPswd());
        //与查询密码比较
        if (!Objects.equals(userPwd,userPwdDB)){
            //若匹配失败，抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        return getAdmin;
    }







    /**
     *  根据提供的关键字，查询数据并显示在页面
     * @param keyword 关键字  用于模糊查询
     * @param pageNum 当前页码
     * @param pageSize 每页显示数量
     * @return
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize
                                       ) {
        //拼接模糊查询条件
        AdminExample adminExample = new AdminExample();
        adminExample.or().andLoginAcctLike("%"+keyword+"%");
        adminExample.or().andEmailLike("%"+keyword+"%");
        adminExample.or().andUsernameLike("%"+keyword+"%");
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        //执行查询语句
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        //获取结果并返回
        PageInfo<Admin> adminPageInfo =new PageInfo<>(admins);
        return adminPageInfo;
    }








    /**
     *      根据传入的id，删除用户数据
     * @param id
     */
    @Override
    public void removeUser(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }







    /**
     *          根据ID查询用户信息
     * @param id
     * @return
     */
    @Override
    public Admin getAdminById(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        return admin;
    }








    /**
     *              修改用户信息
     * @param admin
     */
    @Override
    public void update(Admin admin) {
        //密码加密
        String userPswd = admin.getUserPswd();
        if (userPswd!=null&&userPswd.length()!=0){
            String md5 = CrowdUtils.md5(userPswd);
            admin.setUserPswd(md5);
        }else {
            admin.setUserPswd(null);
        }
        //有选择更新
        adminMapper.updateByPrimaryKeySelective(admin);
    }







    /**
     * 保存用户信息
     */
    @Override
    public int saveAdmin(Admin admin) {
        //1.密码加密
        String userPswd = admin.getUserPswd();
//        String md5 = CrowdUtils.md5(userPswd);
        userPswd = passwordEncoder.encode(userPswd);
        admin.setUserPswd(userPswd);
        //生成创建时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        admin.setCreateTime(time);
        //执行创建
        try {
            int insert = adminMapper.insert(admin);
            int i = 10/0;
            System.out.println(i);
            return insert;
        }catch (Exception e){
            if (e instanceof DuplicateKeyException){
                throw new SaveAdminException("账号已存在");
            }
            throw new DuplicateKeyException("保存失败");
        }
    }


    /**
     * 根据名称获取admin对象
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByLoginAcct(String username) {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andLoginAcctEqualTo(username);
        List<Admin> list = adminMapper.selectByExample(adminExample);
        Admin admin = list.get(0);
        return admin;
    }


}
